package com.paic.common.middleware.util

import com.paic.common.util.ReadPropertyUtils
import org.apache.commons.pool2.impl.GenericObjectPoolConfig
import redis.clients.jedis.JedisPool

object RedisPoolConnection extends Serializable {
  @transient private var pool: JedisPool = null
  def makePool(): Unit = {
    val redisHost = ReadPropertyUtils.getFileProperties("redis-pool.properties", "redis.redisHost")
    val redisPort = ReadPropertyUtils.getFileProperties("redis-pool.properties", "redis.redisPort")
    val redisTimeout = ReadPropertyUtils.getFileProperties("redis-pool.properties", "redis.redisTimeout")
    val maxTotal = ReadPropertyUtils.getFileProperties("redis-pool.properties", "redis.maxTotal")
    val maxIdle = ReadPropertyUtils.getFileProperties("redis-pool.properties", "redis.maxIdle")
    val minIdle = ReadPropertyUtils.getFileProperties("redis-pool.properties", "redis.minIdle")
    val dbIndex = ReadPropertyUtils.getFileProperties("redis-pool.properties", "redis.dbIndex")
    makePool(redisHost, Integer.parseInt(redisPort), Integer.parseInt(redisTimeout), Integer.parseInt(maxTotal), Integer.parseInt(maxIdle), Integer.parseInt(minIdle), true, false, 10000)
  }

  def makePool(redisHost: String, redisPort: Int, redisTimeout: Int,
    maxTotal: Int, maxIdle: Int, minIdle: Int, testOnBorrow: Boolean,
    testOnReturn: Boolean, maxWaitMillis: Long): Unit = {
    if (pool == null) {
      val poolConfig = new GenericObjectPoolConfig()
      poolConfig.setMaxTotal(maxTotal)
      poolConfig.setMaxIdle(maxIdle)
      poolConfig.setMinIdle(minIdle)
      poolConfig.setTestOnBorrow(testOnBorrow)
      poolConfig.setTestOnReturn(testOnReturn)
      poolConfig.setMaxWaitMillis(maxWaitMillis)
      pool = new JedisPool(poolConfig, redisHost, redisPort, redisTimeout)

      val hook = new Thread {
        override def run = pool.destroy()
      }
      sys.addShutdownHook(hook.run)
    }
  }

  def getPool: JedisPool = {
    assert(pool != null)
    pool
  }
}